<%
  id = params[:id]
  environment_permalinks = ['global'] + Environment.pluck(:permalink)
  deploy_groups = Samson::Secrets::Manager.backend.deploy_groups
  deploy_group_groups = environment_permalinks.map do |env_permalink|
    [env_permalink, ['global'] + deploy_groups.select { |dg| dg.environment.permalink == env_permalink }.map(&:permalink)]
  end
  secret = (id ? @secret.merge(Samson::Secrets::Manager.parse_id(id)) : (params[:secret] || {}))
%>
<%= page_title(id ? "Edit #{id}" : "New Secret") %>

<% if id && secret[:deprecated_at] %>
  <div class="alert alert-danger">DEPRECATED: will no longer be resolved for new deploys.</div>
<% end %>

<section>
  <% url = (id ? secret_path(id) : secrets_path) %>
  <% method = (id ? :put : :post) %>

  <%= form_for OpenStruct.new(secret), as: :secret, url: url, method: method, html: {class: "form-horizontal"} do |form| %>
    <fieldset>
      <%= form.input :environment_permalink, label: "Environment", required: true do %>
        <% if id %>
          <%= form.text_field :environment_permalink, disabled: true, class: "form-control" %>
        <% else %>
          <%= form.select :environment_permalink,
            options_for_select(environment_permalinks, secret[:environment_permalink]),
            {include_blank: true}, required: true, **Samson::FormBuilder::LIVE_SELECT_OPTIONS %>
        <% end %>
      <% end %>

      <%= form.input :project_permalink, label: "Project", required: true do %>
        <% if id %>
          <%= form.text_field :project_permalink, disabled: true, class: "form-control" %>
        <% else %>
          <%= form.select :project_permalink,
            options_for_select(@writable_project_permalinks, secret[:project_permalink]),
            {include_blank: true}, required: true, **Samson::FormBuilder::LIVE_SELECT_OPTIONS
          %>
        <% end %>
      <% end %>

      <%= form.input :deploy_group_permalink, label: "Deploy Group", required: true do %>
        <% if id %>
          <%= form.text_field :deploy_group_permalink, disabled: true, class: "form-control" %>
        <% else %>
          <%= form.select :deploy_group_permalink,
            options_for_select([['Loading ...', secret[:deploy_group_permalink]]], secret[:deploy_group_permalink]),
            {include_blank: true}, class: "form-control", required: true %>
        <% end %>
      <% end %>

      <%= form.input :key, input_html: {class: "form-control monospace", disabled: !!id}, required: true %>

      <%= form.input :comment, as: :text_area %>

      <%= form.input :visible, as: :check_box, help: 'Value will remain visible to users of the Samson UI' %>

      <% if @duplicate_secret_error %>
        <div class="alert-danger">
          <%= form.input :allow_duplicates, as: :check_box, help: 'Consider doing this while transitioning to shared secrets.' %>
        </div>
      <% end %>

      <%= form.input :deprecated, as: :check_box, label: "Deprecated #{secret[:deprecated_at]}" do %>
        <%= form.check_box :deprecated_at, {}, secret[:deprecated_at] || Time.now.to_fs(:db), "0" %>
      <% end %>

      <% needs_value = @duplicate_secret_error || !id %>
      <%= form.input :value, field_class: 'col-lg-6' do %>
        <%= form.text_area :value, class: "form-control monospace validate_whitespace", rows: 10, placeholder: ('-- hidden --' if !needs_value), required: needs_value %>
      <% end %>

      <% if id %>
        <%= render 'extras', form: form %>
        <%= render 'sharing_grants', form: form, secret: secret if Samson::Secrets::Manager.sharing_grants? && secret.fetch(:project_permalink) == "global" %>
      <% end %>

      <div class="form-group">
        <div class="col-lg-offset-2 col-lg-10">
          <%= submit_tag 'Save', class: 'btn btn-primary' %>
          <%= submit_tag ResourceController::ADD_MORE, class: 'btn btn-default' %>
          <% if id %>
            <%= link_to "Duplicates", secrets_path(search: {value_from: id}) %> |
            <% if Samson::Secrets::Manager.backend == Samson::Secrets::HashicorpVaultBackend %>
              <% count = Samson::Secrets::Manager.backend.history(id).fetch(:versions).size rescue "error" %>
              <%= link_to "History (#{count})", history_secret_path(id)  %> |
            <% end %>
            <%= link_to_delete secret_path(id) %>
          <% end %>
        </div>
      </div>
    </fieldset>
  <% end %>
</section>

<script>
// when user changes the environment, fill in the possible deploy groups
$(function () {
  var deploy_group_list = <%= deploy_group_groups.to_h.to_json.html_safe %>;
  var $environments = $("#secret_environment_permalink");
  var $deploy_groups = $("#secret_deploy_group_permalink");

  $environments.change(function () {
    var possible_deploy_groups = (deploy_group_list[$environments.val()] || []);
    var val = $deploy_groups.val();

    // clear our current options
    $deploy_groups.empty();

    // fill in the now possible options
    $.each(possible_deploy_groups, function(i, e){
      $deploy_groups.append($("<option>", { value: e, html: e, selected: (e === val) }));
    });
  }).trigger("change");
});
</script>
